package com.moo2u2.android.oaktononthego.locate;

import java.util.List;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.moo2u2.android.oaktononthego.R;
import com.moo2u2.android.oaktononthego.util.ColleagueManager;
import com.moo2u2.android.oaktononthego.util.Util;

public class LocateColleagueActivity extends MapActivity implements
        LocationListener {
    // TODO Link to CRM activity

    private static final int MENU_CENTER_ME = Menu.FIRST + 1;
    private static final int MENU_FIND_NEAREST = Menu.FIRST + 2;

    private MapView map;

    private MapController mapController;

    private LocationManager locationManager;

    private ColleagueOverlay colleagues;
    private MyLocationOverlay myLocation;

    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        final boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

        setContentView(R.layout.locate);
        if (customTitleSupported)
            getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
                    R.layout.window_title);

        map = (MapView) findViewById(R.id.locatemap);

        colleagues = new ColleagueOverlay(this);

        myLocation = new MyLocationOverlay(this, map);

        map.setBuiltInZoomControls(true);
        map.getOverlays().add(myLocation);
        map.getOverlays().add(colleagues);

        mapController = map.getController();
        mapController.setZoom(20);

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
                0, this);

        GeoPoint initGeoPoint =
        // = new GeoPoint((int) (locationManager
        // .getLastKnownLocation(LocationManager.GPS_PROVIDER)
        // .getLatitude() * 1e6), (int) (locationManager
        // .getLastKnownLocation(LocationManager.GPS_PROVIDER)
        // .getLongitude() * 1e6));
        new GeoPoint((int) (-33.837256 * 1E6), (int) (151.207542 * 1E6));
        mapController.animateTo(initGeoPoint);

        ImageButton search = (ImageButton) findViewById(R.id.colleague_search);
        search.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String searchTxt = ((EditText) findViewById(R.id.colleague_search_txt))
                        .getEditableText().toString();
                select(ColleagueManager.searchColleague(
                        LocateColleagueActivity.this, colleagues, searchTxt));
            }

            private void select(ColleagueOverlayItem colleague) {
                if (colleague != null) {
                    colleagues.setFocus(colleague);
                    mapController.animateTo(colleague.getPoint());
                } else {
                    Toast.makeText(
                            LocateColleagueActivity.this,
                            "Couldn't find anyone matching your search. Please try again.",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });

        // Fetch ppl from online
        new AsyncTask<Void, Void, List<Colleague>>() {
            @Override
            protected List<Colleague> doInBackground(Void... arg0) {
                List<Colleague> temp = ColleagueManager.getColleagues();
                return temp;
            }

            @Override
            protected void onPostExecute(List<Colleague> result) {
                if (result != null && !result.isEmpty()) {
                    for (Colleague c : result)
                        colleagues.addColleague(new ColleagueOverlayItem(c));
                }
                Log.i(this.getClass().getSimpleName(), "Added colleagues");
            }
        }.execute();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, MENU_CENTER_ME, Menu.NONE, R.string.center_me)
                .setIcon(android.R.drawable.ic_menu_mylocation);
        menu.add(Menu.NONE, MENU_FIND_NEAREST, Menu.NONE, R.string.find_nearest)
                .setIcon(android.R.drawable.ic_menu_mapmode);
        return true;
    }

    /** {@inheritDoc} */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MENU_CENTER_ME:
            Location mine = locationManager
                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
            mapController.animateTo(new GeoPoint(
                    (int) (mine.getLatitude() * 1e6), (int) (mine
                            .getLongitude() * 1e6)));
            return true;
        case MENU_FIND_NEAREST:
            float shortest = -1;
            ColleagueOverlayItem nearest = null;
            for (ColleagueOverlayItem colleague : colleagues.getColleagues()) {
                float distance = Util.calculateDistance(locationManager
                        .getLastKnownLocation(LocationManager.GPS_PROVIDER),
                        colleague.getPoint());
                if (shortest < 0 || distance < shortest) {
                    shortest = distance;
                    nearest = colleague;
                }
            }
            mapController.animateTo(nearest.getPoint());
            colleagues.setFocus(nearest);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    /** {@inheritDoc} */
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }

    /** {@inheritDoc} */
    @Override
    public void onLocationChanged(Location argLocation) {
        GeoPoint myGeoPoint = new GeoPoint(
                (int) (argLocation.getLatitude() * 1000000),
                (int) (argLocation.getLongitude() * 1000000));

        mapController.animateTo(myGeoPoint);
    }

    @Override
    protected void onResume() {
        super.onResume();
        myLocation.enableMyLocation();
        myLocation.enableCompass();
    }

    @Override
    protected void onPause() {
        super.onPause();
        myLocation.disableMyLocation();
        myLocation.disableCompass();
    }

    /** {@inheritDoc} */
    @Override
    public void onProviderDisabled(String arg0) {
        Toast.makeText(this, "GPS disabled", Toast.LENGTH_SHORT).show();
    }

    /** {@inheritDoc} */
    @Override
    public void onProviderEnabled(String provider) {
        Toast.makeText(this, "GPS enabled", Toast.LENGTH_SHORT).show();
    }

    /** {@inheritDoc} */
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        if (status == 0) {
            Toast.makeText(this, "Location is not available at this time",
                    Toast.LENGTH_SHORT).show();
        } else if (status == 1) {
            // Trying to connect
        } else if (status == 2) {
            // Available
        }

    }

}
